package com.ruoyi.safe.service.impl;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.safe.mapper.ListTypeMapper;
import com.ruoyi.common.core.domain.entity.ListType;
import com.ruoyi.safe.service.IListTypeService;

/**
 * 清单分类Service业务层处理
 *
 * @author buxi
 * @date 2023-11-04
 */
@Service
public class ListTypeServiceImpl implements IListTypeService {
    @Autowired
    private ListTypeMapper listTypeMapper;

    /**
     * 查询清单分类
     *
     * @param id 清单分类主键
     * @return 清单分类
     */
    @Override
    public ListType selectListTypeById(Long id) {
        return listTypeMapper.selectListTypeById(id);
    }

    /**
     * 查询清单分类列表
     *
     * @param listType 清单分类
     * @return 清单分类
     */
    @Override
    public List<ListType> selectListTypeList(ListType listType) {
        return listTypeMapper.selectListTypeList(listType);
    }

    /**
     * 新增清单分类
     *
     * @param listType 清单分类
     * @return 结果
     */
    @Override
    public int insertListType(ListType listType) {
        int i = listTypeMapper.selectListTypeCount(listType.getTypeNo(), listType.getId());
        if (i > 0) {
            throw new RuntimeException("类型编码已存在");
        }
        if (listType.getParentId() == 0) {
            listType.setAncestors(listType.getTypeNo());
        } else {
            ListType listType1 = listTypeMapper.selectListTypeByTypeNo(listType.getParentId());
            listType.setAncestors(listType1.getAncestors() + "," + listType.getTypeNo());
        }
        listType.setCreateBy(SecurityUtils.getUsername());
        listType.setCreateTime(DateUtils.getNowDate());
        return listTypeMapper.insertListType(listType);
    }

    /**
     * 修改清单分类
     *
     * @param listType 清单分类
     * @return 结果
     */
    @Override
    public int updateListType(ListType listType) {
        if (listTypeMapper.selectListTypeCount(listType.getTypeNo(), listType.getId()) > 0) {
            throw new RuntimeException("类型编码已存在");
        }
        if (listType.getParentId() == 0) {
            listType.setAncestors(listType.getTypeNo());
        } else {
            ListType listType1 = listTypeMapper.selectListTypeByTypeNo(listType.getParentId());
            listType.setAncestors(listType1.getAncestors() + "," + listType.getTypeNo());
        }
        listType.setUpdateBy(SecurityUtils.getUsername());
        listType.setUpdateTime(DateUtils.getNowDate());
        return listTypeMapper.updateListType(listType);
    }

    /**
     * 批量删除清单分类
     *
     * @param ids 需要删除的清单分类主键
     * @return 结果
     */
    @Override
    public int deleteListTypeByIds(Long[] ids) {
        int i=0;
        if(0 == listTypeMapper.checkIds(ids)){
            i = listTypeMapper.deleteListTypeByIds(ids);
        }
        return i;
    }

    /**
     * 删除清单分类信息
     *
     * @param id 清单分类主键
     * @return 结果
     */
    @Override
    public int deleteListTypeById(Long id) {
        return listTypeMapper.deleteListTypeById(id);
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param listTypes 类型列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildTypeTreeSelect(List<ListType> listTypes) {
        List<ListType> typeTrees = buildTypeTree(listTypes);
        return typeTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }


    /**
     * 构建前端所需要树结构
     *
     * @param listTypes 类型列表
     * @return 树结构列表
     */
    @Override
    public List<ListType> buildTypeTree(List<ListType> listTypes) {
        List<ListType> returnList = new ArrayList<ListType>();
        List<String> tempList = listTypes.stream().map(ListType::getTypeNo).collect(Collectors.toList());
        for (ListType archivesType : listTypes) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(String.valueOf(archivesType.getParentId()))) {
                recursionFn(listTypes, archivesType);
                returnList.add(archivesType);
            }
        }
        if (returnList.isEmpty()) {
            returnList = listTypes;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<ListType> list, ListType t) {
        // 得到子节点列表
        List<ListType> childList = getChildList(list, t);
        // 增加层级
        for (int i = 0; i < childList.size(); i++) {
            childList.get(i).setLevel(t.getLevel() + 1);
        }
        t.setChildren(childList);
        for (ListType tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<ListType> getChildList(List<ListType> list, ListType t) {
        List<ListType> tlist = new ArrayList<ListType>();
        Iterator<ListType> it = list.iterator();
        while (it.hasNext()) {
            ListType n = (ListType) it.next();
            if (StringUtils.isNotNull(n.getParentId())) {
                if (String.valueOf(n.getParentId()).equals(t.getTypeNo())) {
                    tlist.add(n);
                }
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<ListType> list, ListType t) {
        return getChildList(list, t).size() > 0;
    }

    public <t> List<t> processList(List<t> list) {
        List<ListType> listTypes = listTypeMapper.selectListTypeList(new ListType());

        for (t item : list) {
            try {
                Field typeNoField = item.getClass().getDeclaredField("typeNo");
                typeNoField.setAccessible(true);

                String typeNoValue = (String) typeNoField.get(item);

                ListType listType = listTypes.stream()
                        .filter(s -> s.getId().toString().equals(typeNoValue))
                        .findFirst()
                        .orElse(null);

                if (listType != null) {
                    List<String> typeNames = Arrays.stream(listType.getAncestors().split(","))
                            .map(s -> listTypes.stream()
                                    .filter(s1 -> s1.getTypeNo().equals(s))
                                    .findFirst()
                                    .map(ListType::getTypeName)
                                    .orElse(null))
                            .collect(Collectors.toList());
                    typeNoField.set(item, String.join("/", typeNames));
                } else {
                    typeNoField.set(item, "");
                }

            } catch (NoSuchFieldException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        return list;
    }

}
